<?php
namespace Index\Controller;
use Think\Controller;
class QuestionController extends CommonController{
	//展示问题
	public function indexAction(){
		//$id是从Ask控制器传过来的问题页面的参数，跳转到对应的问题页面，这里用get方法接收
		$id= I('get.id','');
		if (!empty($id)) {
			//浏览量刷新功能
			$this->autoadd('question','view',$id);
			// 获取用户数据,用户表的id=问题表的uid，通过这样的方式，把两张表连起来，取用户数据
			$sql = "select t1.*,t2.username,t2.id from question t1 left join user t2 on t1.uid=t2.id where t1.id='{$id}'";
			$question = M()->query($sql);
			
			//$question得到的结果是同时查询到某个用户di的用户表和问题表对应的信息，所以$question是一个数组，current函数，取数组当前项
			$question = current($question);
			//$question['content']取数组中的content值，也就是问题内容，它会把标签符号也转译了，用htmlspecialchars_decode函数反转译出来
			$question['content'] = htmlspecialchars_decode($question['content']);
			//Ftime方法，写在核心方法function里，将产生的当前时间戳处理成一个小时前，几分钟前显示，该方法写在ThinkPHP里的Common下的functions.php方法里
			$question['create_time'] = Ftime(date('Y-m-d H:i:s',$question['create_time']));

			// 获取当前问题的分类数据
			$sql = "select t1.cname,t1.id from category t1 left join category_question t2 on t1.id = t2.cid where t2.qid= '{$id}'";

			$category = M()->query($sql);

			//回答问题，查询数据库问题表
			$answersql = "select t1.username,t1.face,t2.* from user t1 left join answer t2 on t1.id = t2.uid where qid='{$id}'";

			$answerres = M()->query($answersql);
			// var_dump($answerres);exit;

			foreach ($answerres as $key => $value) {
				$answerres[$key]['create_time'] = Ftime(date('Y-m-d H:i:s',$answerres[$key]['create_time']));
			}	

			//统计回答数
			// $answer_numsql = "select * from answer where qid='{$id}'";

			// $answer_count = current(M()->query($answer_numsql));

			// $this->assign('answer_count',$answer_count);

			$this->assign('answerres',$answerres);

			$this->assign('category',$category);

			$this->assign('question',$question);

			$this->display();
		}else{
			$this->error('非法请求',U('index/index/index'));
		}		
	}

	// 回答问题并将答案推到问题页面
	public function answerAction(){

		// var_dump($_POST);exit;

		if (IS_POST) {
			// var_dump($_POST);exit;
			$qid = $_POST['qid'];
			// var_dump($qid);exit;
			$uid = $_SESSION['id'];
			$username = $_SESSION['username'];
			$create_time = time();
			$face = $_SESSION['face'];
			$content = $_POST['answer'];
			$sql = "insert into answer (qid,uid,content,create_time) value('{$qid}','{$uid}','{$content}','{$create_time}')";
			$res = M()->execute($sql);

			if ($res) {
				$answernumsql = "update question set answer_num =answer_num +1 where id={$qid}";
				M()->execute($answernumsql);
				$this->error('回答成功',U('index/question/index',array('id'=>$qid)));
			}else{
				$this->error('非法请求，请先登录',U('index/index/index',array('id'=>$qid)));
			}
		}
	}






}